package com.tanhua.sso.controller;

import com.tanhua.domain.pojo.User;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.sso.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.agreement.jpake.JPAKEUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Sabrina
 * @Date:2025/06/12/11:15
 * @Description:
 */
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param param
     * @return
     */
    @PostMapping("/loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){
        log.info("用户登录: {}", param);

        try {
            String mobile = param.get("phone");
            String code = param.get("verificationCode");
            String token = this.userService.login(mobile, code);

            if (StringUtils.isNotEmpty(token)){
                //登录成功
                String[] ss = StringUtils.split(token, "|");
                Boolean isNew = Boolean.valueOf(ss[0]);
                String tokenStr = ss[1];

                Map<String,Object> result = new HashMap<>();
                result.put("isNew",isNew);
                result.put("token",tokenStr);

                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        //没有成功登录,走到这,return错误500
        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("登录失败");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());//HttpStatus.INTERNAL_SERVER_ERROR:错误500
    }

    /**
     * 根据token查询用户数据
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
